package com.harassment.interception.ui.fragments.listManagement.whiteListFragment;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.DialogInterface;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.harassment.interception.R;
import com.harassment.interception.base.HIApplication;
import com.harassment.interception.data.databases.HIDBUtil;
import com.harassment.interception.data.databases.HIDatabase;
import com.harassment.interception.data.databases.entities.WhiteList;
import com.harassment.interception.ui.fragments.bottomFragment.BottomBar;
import com.harassment.interception.ui.fragments.dialogFragments.ConfirmDialog;
import com.harassment.interception.ui.fragments.dialogFragments.OnNegativeClickListener;
import com.harassment.interception.ui.fragments.dialogFragments.OnPositiveClickListener;
import com.harassment.interception.ui.fragments.listManagement.dialogFragments.AddWhiteListDialog;
import com.harassment.interception.ui.fragments.listManagement.dialogFragments.SelectActionDialog;
import com.harassment.interception.ui.fragments.recyclerView.OnItemClickListener;
import com.harassment.interception.ui.fragments.recyclerView.OnItemLongClickListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import io.reactivex.Completable;
import io.reactivex.CompletableEmitter;
import io.reactivex.CompletableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Action;
import io.reactivex.schedulers.Schedulers;

public class WhiteListAdapter extends RecyclerView.Adapter<WhiteListAdapter.ViewHolder> implements OnItemClickListener, OnItemLongClickListener {
    private static final String TAG = "WhiteListAdapter";
    private List<WhiteList> mWhiteLists;
    private HashMap<Integer, Boolean> mSelectList;
    private BottomBar mBottomBar;
    private boolean mSelectMode;
    private OnItemClickListener mOnItemClickListener;
    private OnItemLongClickListener mOnItemLongClickListener;
    private Fragment mFragment;
    private ConfirmDialog mConfirmDialog;
    private AddWhiteListDialog mAddWhiteListDialog;
    private SelectActionDialog mSelectActionDialog;

    @SuppressLint("CheckResult")
    public WhiteListAdapter(BottomBar bottomBar, Fragment fragment) {
        mFragment = fragment;
        mConfirmDialog = new ConfirmDialog();
        mBottomBar = bottomBar;
        mSelectList = new HashMap<>();
        mOnItemLongClickListener = this;
        mOnItemClickListener = this;
        mSelectMode = false;
        mSelectActionDialog = new SelectActionDialog();
        mAddWhiteListDialog = new AddWhiteListDialog();
        Completable.create(new CompletableOnSubscribe() {
            @Override
            public void subscribe(CompletableEmitter emitter) throws Exception {
                mWhiteLists = HIDBUtil.getWhiteListDao().getAllWhiteList();
                selectInit(mWhiteLists.size(), false);
                emitter.onComplete();
            }
        })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action() {
                    @Override
                    public void run() throws Exception {
                        WhiteListAdapter.this.notifyDataSetChanged();
                    }
                });
        mSelectActionDialog.setOnItemClickListener(new com.harassment.interception.ui.fragments.dialogFragments.OnItemClickListener() {
            @Override
            public void onItemClickListener(View v) {
                selectAction(mSelectActionDialog.getDialog(), v);
            }
        });
        mAddWhiteListDialog.setOnPositiveClickListener(new OnPositiveClickListener() {
            @Override
            public void onPositiveClickListener(DialogInterface dialog, int which) {
                update(mAddWhiteListDialog.getDialogView());
                dialog.cancel();
            }
        });
        mAddWhiteListDialog.setOnNegativeClickListener(new OnNegativeClickListener() {
            @Override
            public void onNegativeClickListener(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });
    }


    private void selectAction(Dialog dialog, View view) {
        switch (view.getId()) {
            case R.id.select_update:
                selectUpdate();
                break;
            case R.id.select:
                select();
                break;
        }
        dialog.cancel();
    }

    @SuppressLint("CheckResult")
    private void update(final View view) {
        Completable.create(new CompletableOnSubscribe() {
            @Override
            public void subscribe(CompletableEmitter emitter) throws Exception {
                addWhiteList();
                emitter.onComplete();
            }

            private void addWhiteList() {
                WhiteList WhiteList = mWhiteLists.get(mSelectActionDialog.getItemPosition());
                EditText number = view.findViewById(R.id.input_number);
                if (number.getText().toString().length() == 0) {
                    return;
                }
                EditText remark = view.findViewById(R.id.input_remark);
                RadioButton dark = view.findViewById(R.id.radio_dark);
                RadioButton accurate = view.findViewById(R.id.radio_accurate);
                CheckBox phone = view.findViewById(R.id.not_intercept_phone);
                CheckBox sms = view.findViewById(R.id.not_intercept_sms);

                WhiteList.setNumber(number.getText().toString());
                WhiteList.setRemark(remark.getText().toString());
                if (dark.isChecked()) {
                    WhiteList.setModel(HIDatabase.DARK_MODEL);
                } else if (accurate.isChecked()) {
                    WhiteList.setModel(HIDatabase.ACCURATE_MODEL);
                }
                WhiteList.setPhone(phone.isChecked());
                WhiteList.setSms(sms.isChecked());

                HIDBUtil.getWhiteListDao().updateWhiteList(WhiteList);

            }
        })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action() {
                    @Override
                    public void run() throws Exception {
                        WhiteListAdapter.this.notifyItemChanged(mSelectActionDialog.getItemPosition());
                        Toast.makeText(getFragment().getActivity(), R.string.update_success, Toast.LENGTH_SHORT).show();
                    }
                });
    }

    private void selectUpdate() {
        View view = getFragment().getLayoutInflater().inflate(R.layout.dialog_add_white_list, null);
        EditText number = view.findViewById(R.id.input_number);
        EditText remark = view.findViewById(R.id.input_remark);
        RadioButton dark = view.findViewById(R.id.radio_dark);
        RadioButton accurate = view.findViewById(R.id.radio_accurate);
        CheckBox phone = view.findViewById(R.id.not_intercept_phone);
        CheckBox sms = view.findViewById(R.id.not_intercept_sms);

        WhiteList WhiteList = mWhiteLists.get(mSelectActionDialog.getItemPosition());
        number.setText(WhiteList.getNumber());
        remark.setText(WhiteList.getRemark());
        if (WhiteList.getModel() == HIDatabase.DARK_MODEL) {
            dark.setChecked(true);
        } else {
            accurate.setChecked(true);
        }
        phone.setChecked(WhiteList.isPhone());
        sms.setChecked(WhiteList.isSms());

        mAddWhiteListDialog.setView(view);
        mAddWhiteListDialog.show(getFragment().getChildFragmentManager(), AddWhiteListDialog.TAG);
    }

    private void select() {
        if (mSelectMode) {
            return;
        }
        mSelectMode = true;
        mSelectList.put(mSelectActionDialog.getItemPosition(), true);
        this.notifyDataSetChanged();
        mBottomBar.showOperateView();
        initOperateBarListener();
    }


    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_white_item, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull final ViewHolder holder, int position) {
        WhiteList whiteList = mWhiteLists.get(position);
        if (whiteList.getModel() == HIDatabase.DARK_MODEL) {
            holder.number.setText(whiteList.getNumber() + "*");
        } else {
            holder.number.setText(whiteList.getNumber());
        }
        holder.remark.setText(whiteList.getRemark());
        if (whiteList.isPhone()) {
            holder.telephone.setVisibility(View.VISIBLE);
        } else {
            holder.telephone.setVisibility(View.GONE);
        }
        if (whiteList.isSms()) {
            holder.sms.setVisibility(View.VISIBLE);
        } else {
            holder.sms.setVisibility(View.GONE);
        }

        if (mSelectMode) {
            holder.select.setVisibility(View.VISIBLE);
            holder.select.setChecked(mSelectList.get(position));
        } else {
            holder.select.setVisibility(View.GONE);
        }

        if (mOnItemClickListener != null) {
            View.OnClickListener onClickListener = new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int position = holder.getLayoutPosition();
                    mOnItemClickListener.onItemClick(holder.itemView, position);
                }
            };
            holder.phoneItem.setOnClickListener(onClickListener);
            holder.select.setOnClickListener(onClickListener);
        }
        if (mOnItemLongClickListener != null) {
            holder.phoneItem.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    int position = holder.getLayoutPosition();
                    return mOnItemLongClickListener.onItemLongClick(holder.itemView, position);
                }
            });
        }
    }

    @Override
    public int getItemCount() {
        return (mWhiteLists == null) ? 0 : mWhiteLists.size();
    }

    public void selectInit(int length, boolean selectMode) {
        for (int i = 0; i < length; i++) {
            mSelectList.put(i, selectMode);
        }
    }

    @Override
    public void onItemClick(View view, int position) {
        if (!mSelectMode) {
            return;
        }
        if (mSelectList.get(position)) {
            mSelectList.put(position, false);
        } else {
            mSelectList.put(position, true);
        }
        this.notifyItemChanged(position);
    }

    @Override
    public boolean onItemLongClick(View view, int position) {
        mSelectActionDialog.show(getFragment().getChildFragmentManager(),SelectActionDialog.TAG);
        mSelectActionDialog.setItemPosition(position);
        return true;
    }

    private void initOperateBarListener() {
        ImageView selectAll;
        ImageView selectClose;
        ImageView selectDelete;
        LinearLayout view = mBottomBar.getOperateView();
        selectAll = view.findViewById(R.id.select_all);
        selectClose = view.findViewById(R.id.select_close);
        selectDelete = view.findViewById(R.id.select_delete);

        selectAll.setOnClickListener(new View.OnClickListener() {
            private boolean selectMode = false;

            @Override
            public void onClick(View v) {
                if (selectMode) {
                    selectInit(mWhiteLists.size(), false);
                    selectMode = false;
                } else {
                    selectInit(mWhiteLists.size(), true);
                    selectMode = true;
                }
                WhiteListAdapter.this.notifyDataSetChanged();
            }
        });
        selectClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mSelectMode = false;
                mBottomBar.showBottomNavigationView();
                WhiteListAdapter.this.notifyDataSetChanged();
                selectInit(mWhiteLists.size(), false);
            }
        });
        selectDelete.setOnClickListener(new View.OnClickListener() {
            @SuppressLint("CheckResult")
            @Override
            public void onClick(View v) {
                Log.d(TAG, "onClick: 开始删除");
                Completable.create(new CompletableOnSubscribe() {
                    @Override
                    public void subscribe(final CompletableEmitter emitter) throws Exception {
                        mConfirmDialog.setOnPositiveClickListener(new OnPositiveClickListener() {
                            @Override
                            public void onPositiveClickListener(DialogInterface dialog, int which) {
                                delete();
                                emitter.onComplete();
                            }
                        });
                        mConfirmDialog.setOnNegativeClickListener(new OnNegativeClickListener() {
                            @Override
                            public void onNegativeClickListener(DialogInterface dialog, int which) {
                                dialog.cancel();
                            }
                        });
                        mConfirmDialog.show(mFragment.getChildFragmentManager(), ConfirmDialog.TAG);
                    }

                    private void delete() {
                        Log.d(TAG, "subscribe: 子线程开启");
                        List<WhiteList> tempList = new ArrayList<>();
                        //InterceptedPhones -> tempInterceptedPhones
                        Log.d(TAG, "subscribe: InterceptedPhones -> tempInterceptedPhones");
                        for (int i = 0; i < mSelectList.size(); i++) {
                            if (mSelectList.get(i)) {
                                tempList.add(mWhiteLists.get(i));
                            }
                        }
                        //tempLists -> phones[]
                        Log.d(TAG, "subscribe: tempLists -> phones[]");
                        WhiteList[] whiteLists = new WhiteList[tempList.size()];
                        tempList.toArray(whiteLists);
                        //phones[] -> Database
                        Log.d(TAG, "subscribe: phones[] -> Database");
                        HIDBUtil.getWhiteListDao().deleteWhiteList(whiteLists);
                        //new mWhiteLists
                        Log.d(TAG, "subscribe: new mWhiteLists");
                        mWhiteLists = HIDBUtil.getWhiteListDao().getAllWhiteList();
                        mSelectList = new HashMap<>();
                        selectInit(mWhiteLists.size(), false);
                    }
                })
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Action() {
                            @Override
                            public void run() throws Exception {
                                Log.d(TAG, "run: notifyDataSetChanged");
                                mSelectMode = false;
                                WhiteListAdapter.this.notifyDataSetChanged();
                                mBottomBar.showBottomNavigationView();
                                Toast.makeText(HIApplication.getContext(), "已删除！", Toast.LENGTH_SHORT).show();
                            }
                        });
            }
        });
    }

    public List<WhiteList> getWhiteLists() {
        return mWhiteLists;
    }

    public void setWhiteLists(List<WhiteList> whiteLists) {
        mWhiteLists = whiteLists;
    }

    public HashMap<Integer, Boolean> getSelectList() {
        return mSelectList;
    }

    public void setSelectList(HashMap<Integer, Boolean> selectList) {
        mSelectList = selectList;
    }

    public BottomBar getBottomBar() {
        return mBottomBar;
    }

    public void setBottomBar(BottomBar bottomBar) {
        mBottomBar = bottomBar;
    }

    public boolean isSelectMode() {
        return mSelectMode;
    }

    public void setSelectMode(boolean selectMode) {
        mSelectMode = selectMode;
    }

    public OnItemClickListener getOnItemClickListener() {
        return mOnItemClickListener;
    }

    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        mOnItemClickListener = onItemClickListener;
    }

    public OnItemLongClickListener getOnItemLongClickListener() {
        return mOnItemLongClickListener;
    }

    public void setOnItemLongClickListener(OnItemLongClickListener onItemLongClickListener) {
        mOnItemLongClickListener = onItemLongClickListener;
    }

    public Fragment getFragment() {
        return mFragment;
    }

    public void setFragment(Fragment fragment) {
        mFragment = fragment;
    }

    public ConfirmDialog getConfirmDialog() {
        return mConfirmDialog;
    }

    public void setConfirmDialog(ConfirmDialog confirmDialog) {
        mConfirmDialog = confirmDialog;
    }

    static class ViewHolder extends RecyclerView.ViewHolder {
        TextView number;
        TextView remark;
        TextView telephone;
        TextView sms;
        ViewGroup phoneItem;
        CheckBox select;

        public ViewHolder(View itemView) {
            super(itemView);
            phoneItem = itemView.findViewById(R.id.recycler_white_item);
            select = itemView.findViewById(R.id.select);
            number = itemView.findViewById(R.id.number);
            remark = itemView.findViewById(R.id.remark);
            telephone = itemView.findViewById(R.id.telephone);
            sms = itemView.findViewById(R.id.sms);
        }
    }
}
